package com.cx.base.day19_thread;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;

/**
 * @Author: robert.song
 * @Date: Created in 2021/8/31
 */
public class Thread_13_1_原子性_原子整型 {
    public static void main(String[] args) {
        AtomicInteger i = new AtomicInteger(0);
        System.out.println(i.incrementAndGet());
        System.out.println(i.get());
        System.out.println(i.getAndIncrement());
        System.out.println(i.get());
//        基于cas锁的增加方法
        i.addAndGet(1);
//        源码其实就是下面的cas
//        while (true){
//            int prev = i.get();
//            int next = prev*10;
//            if(i.compareAndSet(prev,next)){
//                break;
//            }
//        }

//        更复杂的原子操作：自定义操作
        i.updateAndGet(value -> value * 10);
        System.out.println(i);
//      原理如下方法
        System.out.println(updateAndGet(i, p -> p / 2));

    }

    public static AtomicInteger updateAndGet(AtomicInteger i, IntUnaryOperator operator) {
        while (true) {
            int prev = i.get();
            int next = operator.applyAsInt(prev);
            if (i.compareAndSet(prev, next)) {
                break;
            }
        }
        return i;
    }
}